/*
 * $Id: sem.c 50 2009-02-10 05:48:05Z hyunghwan.chung $
 *
   Copyright 2005-2009 Chung, Hyung-Hwan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an  BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#include <xp/bas/thr.h>
#include <xp/bas/sem.h>
#include <xp/bas/time.h>
#include <xp/bas/stdio.h>

xp_sem_t sem;

int dummy (xp_thr_t* thr)
{
	int i;

	if (xp_sem_acquire (&sem) == -1) 
		xp_printf (XP_T("cannot acquire semaphore\n"));

	for (i = 0; i < 5; i++) {
		xp_printf (XP_T("dummy. %i\n"), i);
		xp_sleep (1000);
	}

	if (xp_sem_release (&sem) == -1) 
		xp_printf (XP_T("cannot release semaphore\n"));

	return 0;
}

int xp_main ()
{
	xp_thr_t thr1, thr2, thr3;

	if (xp_thr_open (&thr1, dummy, 0) == XP_NULL) {
		xp_printf (XP_T("cannot open thread\n"));
		return -1;
	}
	if (xp_thr_open (&thr2, dummy, 0) == XP_NULL) {
		xp_printf (XP_T("cannot open thread\n"));
		return -1;
	}
	if (xp_thr_open (&thr3, dummy, 0) == XP_NULL) {
		xp_printf (XP_T("cannot open thread\n"));
		return -1;
	}

	if (xp_sem_open (&sem, 2) == XP_NULL) {
		xp_printf (XP_T("cannot create a semaphore\n"));
		return -1;
	}

	if (xp_thr_start (&thr1, 0) == -1) {
		xp_printf (XP_T("cannot start thread\n"));
		return -1;
	}
	if (xp_thr_start (&thr2, 0) == -1) {
		xp_printf (XP_T("cannot start thread\n"));
		return -1;
	}
	if (xp_thr_start (&thr3, 0) == -1) {
		xp_printf (XP_T("cannot start thread\n"));
		return -1;
	}

	xp_thr_join (&thr1);
	xp_thr_join (&thr2);
	xp_thr_join (&thr3);

	xp_sem_close (&sem);

	xp_thr_close (&thr1);
	xp_thr_close (&thr2);
	xp_thr_close (&thr3);

	return 0;
}
